import React, { Component } from 'react';
import { Button, View, ScrollView, Text, AsyncStorage, TouchableNativeFeedback } from 'react-native';
import RNFileSelector from 'react-native-file-selector';
import PlayBar from '../components/PlayBar'


const getAudioTimeString = (seconds) => {
    const h = parseInt(seconds / (60 * 60));
    const m = parseInt(seconds % (60 * 60) / 60);
    const s = parseInt(seconds % 60);

    return ((h < 10 ? '0' + h : h) + ':' + (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s));
}

const chooseFile = () => {
    return new Promise((resolve, reject) => {
        let path
        AsyncStorage.getItem("path").then((value) => {
            if (value) {
                path = value
            }
            RNFileSelector.Show(
                {
                    title: '选择音频',
                    path,
                    onDone: (path) => {
                        AsyncStorage.setItem("path", path.substring(0, path.lastIndexOf("/"))).then(() => {
                            resolve(path)
                        })
                    },
                    onCancel: () => {
                        reject("cancel")
                    }
                }
            )
        })
    })
}

const ItemBar = ({ item, index, that }) => {
    return (
        <View style={{ flexDirection: "row", alignItems: "center" }}>
            <TouchableNativeFeedback
                onPress={() => {
                    that.setSound(index)
                }}
                style={{ flex: 1 }}
                background={TouchableNativeFeedback.SelectableBackground()}>
                <View style={{ flex: 1 }}>
                    <Text>{item.path}</Text>
                    <Text>{getAudioTimeString(item.seconds)}</Text>
                </View>
            </TouchableNativeFeedback>
            <Button title="更换" onPress={() => {
                that.changeData(index)
            }}></Button>
            <Button title="删除" color="red" onPress={() => {
                that.deleteData(index)
            }}></Button>
        </View>
    )
}

let that;

export default class HomeScreen extends Component {
    static navigationOptions = {
        headerTitle: <Text>播放器</Text>,
        headerRight: (
            <Button
                onPress={() => {
                    chooseFile().then((path) => {
                        return that.addData(path)
                    }).then(() => {
                        that.getData()
                    }).catch(e => {
                        console.log(e)
                    })
                }}
                title="添加"
            />
        ),
    };
    constructor() {
        super();
        that = this
        this.state = {
            path: "",
            list: [],
            index: 0
        }
    }
    componentDidMount() {
        this.getData()
    }
    getData = async () => {
        let list = await AsyncStorage.getItem("list")
        if (list) {
            list = JSON.parse(list)
        }
        else {
            list = []
        }
        let index = await AsyncStorage.getItem("index")
        this.setState({
            list,
            index: index || -1
        })
        this.setSound(this.state.index)
    }
    addData = async (path) => {
        let list = await AsyncStorage.getItem("list")
        if (list) {
            list = JSON.parse(list)
        }
        else {
            list = []
        }

        list.push({
            path,
            seconds: 0
        })

        await AsyncStorage.setItem("list", JSON.stringify(list))
        this.setState({ list })
    }
    changeData = async (index) => {
        this.refs.play.pause();
        let list = await AsyncStorage.getItem("list")
        if (list) {
            list = JSON.parse(list)
        }
        else {
            list = []
        }

        let path = await chooseFile()
        list[index].path = path
        list[index].seconds = 0
        await AsyncStorage.setItem("list", JSON.stringify(list))

        this.getData()
    }
    deleteData = async (index) => {
        let list = await AsyncStorage.getItem("list")
        if (list) {
            list = JSON.parse(list)
        }
        else {
            list = []
        }
        if (list.length > 0) {
            list.splice(index, 1);
        }

        if (this.state.index >= index) {
            await this.setSound(this.state.index - 1)
        }
        await AsyncStorage.setItem("list", JSON.stringify(list))
        this.getData()
    }
    setSound = async (index) => {
        await AsyncStorage.setItem("index", index.toString())
        if (this.state.list.length > index && index >= 0) {
            this.setState({
                index,
                seconds: this.state.list[index].seconds,
                path: this.state.list[index].path
            })
            this.refs.play.setSound()
        }
        else {
            this.setState({
                index,
                seconds: 0,
                path: ''
            })
            this.refs.play.release()
        }
    }
    saveSeconds = async (seconds) => {
        let list = await AsyncStorage.getItem("list")
        if (list) {
            list = JSON.parse(list)
        }
        else {
            list = []
        }
        if (list.length > this.state.index && this.state.index >= 0) {
            list[this.state.index].seconds = seconds
            await AsyncStorage.setItem("list", JSON.stringify(list))
            this.setState({ list })
        }
    }
    report = async (seconds) => {
        await this.saveSeconds(seconds)
        this.setState({ seconds })
    }
    render() {
        return (
            <View style={{ flex: 1 }}>
                <ScrollView>
                    {
                        this.state.list.map((o, index) => {
                            return (
                                <ItemBar key={index} item={o} index={index} that={this}></ItemBar>
                            )
                        })
                    }
                </ScrollView>
                {
                    <View>
                        <PlayBar ref="play" report={this.report} path={this.state.path} seconds={this.state.seconds}></PlayBar>
                    </View>
                }
            </View>
        );
    }
}